const express = require('express');
const path = require('path');
const cors = require('cors');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

// 路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 翻译API路由 - 转发到Python后端
app.post('/api/translate', async (req, res) => {
    try {
        const { text, sourceLang, targetLangs } = req.body;
        
        // 调用Python后端服务
        const response = await fetch('http://127.0.0.1:5000/translate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                text,
                sourceLang,
                targetLangs
            })
        });

        if (!response.ok) {
            throw new Error('翻译服务请求失败');
        }

        const data = await response.json();
        res.json(data);
    } catch (error) {
        console.error('翻译请求错误:', error);
        res.status(500).json({ error: '翻译服务暂时不可用' });
    }
});

// Excel导出API路由 - 转发到Python后端
app.post('/api/export-excel', async (req, res) => {
    try {
        const { originalText, sourceLang, translationResults } = req.body;
        
        // 调用Python后端服务
        const response = await fetch('http://127.0.0.1:5000/export-excel', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                originalText,
                sourceLang,
                translationResults
            })
        });

        if (!response.ok) {
            throw new Error('Excel导出服务请求失败');
        }

        // 将Excel文件流式传输回客户端
        const arrayBuffer = await response.arrayBuffer();
        
        response.headers.forEach((value, name) => {
            res.setHeader(name, value);
        });
        
        res.send(Buffer.from(arrayBuffer));
    } catch (error) {
        console.error('Excel导出请求错误:', error);
        res.status(500).json({ error: 'Excel导出服务暂时不可用' });
    }
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`前端服务器运行在 http://localhost:${PORT}`);
});